/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.absisgroup.nt;

import com.absisgroup.nsc.utilities.GenericServlet;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Hue
 */
public class LuuLoaiHangHoa extends GenericServlet {

    @Override
    public int process(final Connection con, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        JSONArray records = new JSONArray(request.getParameter("records"));
        save(con, records);
        con.commit();
        final JSONObject jsObj = new JSONObject();
        jsObj.put("success", true);
        writeToResponse(response, jsObj.toString());

        return DONT_RUN_JSP;
    }
    
    private void save(Connection con, JSONArray records) throws Exception {
        String strQuery = "insert into PRODUCT_TYPES(PRODT_NAME) values(?)";
        PreparedStatement pStmt = con.prepareStatement(strQuery);
        int iLength = records.length();
        for(int i=0; i<iLength; i++) {
            JSONObject jsObj = records.getJSONObject(i);
            String name = getString(jsObj, "name");
            if(name != null && !name.isEmpty()) {
                pStmt.setString(1, name);
                pStmt.addBatch();
            }
        }
        pStmt.executeBatch();
        pStmt.close();
    }

    @Override
    protected boolean useConnection() {
        return true;
    }
    
}
